package eerbaar.shared.persist.internal.lib;

import java.util.List;

import eerbaar.action.IAction;
import eerbaar.action.ActionFactory;
import eerbaar.context.IParams;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.IAttribute;
import eerbaar.shared.tree.IAttributes;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;

public class ActionPersister implements IPersister<IAction> {

    public static final String NAME = "action";

    private IAction target;

    public ActionPersister() {
        //
    }

    public ActionPersister(IAction target) {
        this.target = target;
    }

    public ActionPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IAction> getRegistertedInterface() {
        return IAction.class;
    }

    @Override
    public ISaver<?>[] getSavableChildren() {

        IParams params = this.target.getParams();
        ParamsPersister p = new ParamsPersister(params);
        return new ISaver<?>[] { p };
    }

    @Override
    public String getSavableName() {

        return NAME;
    }

    @Override
    public IAction getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> saver) {
        return false;
    }

    @Override
    public IAction load(INode node) {
        assert (node != null);

        IAttributes attributes = node.getAttributes();
        String type = attributes.get(String.class, "type");

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);

        IParams params = null;
        List<INode> list = NodeCmdFactory.findChildren(node,
                ParamsPersister.NAME);
        for (INode n : list) {
            try {
                params = service.load(IParams.class, n);
            } catch (GameException e) {
                e.printStackTrace();
            }
        }

        IAction result = ActionFactory.createAction(type, params);

        IAttribute<?> a = attributes.get("priority");
        if (a != null) {
            int priority = attributes.get(Integer.class, "priority");
            result.setPriority(priority);
        }

        return result;
    }

    @Override
    public void saveAttributes(INode node) {

        IAttributes a = node.getAttributes();

        String type = this.target.getType();
        a.set(String.class, "type", type);
        a.set(Integer.class, "priority", this.target.getPriority());
    }

    @Override
    public void setTarget(IAction obj) {
        this.target = obj;
    }

}
